package com.ljyh.forum.controller;

import com.ljyh.forum.config.JwtUtil;
import com.ljyh.forum.service.LikeService;
import com.ljyh.forum.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 点赞控制器
 */
@RestController
@RequestMapping("/posts/{postId}/like")
@Tag(name = "点赞接口", description = "点赞相关接口")
public class LikeController {

    @Autowired
    private LikeService likeService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping
    @Operation(summary = "点赞/取消点赞帖子")
    public ApiResponse<Void> toggleLike(@PathVariable Long postId) {
        // 从JWT token中获取用户ID
        Long userId = SecurityUtils.getCurrentUserId(jwtUtil);
        
        if (userId == null) {
            return ApiResponse.error(401, "用户未认证");
        }
        
        boolean isLiked = likeService.toggleLike(postId, userId);
        String message = isLiked ? "点赞成功" : "取消点赞成功";
        
        return ApiResponse.success(message, null);
    }

    @GetMapping
    @Operation(summary = "检查是否点赞")
    public ApiResponse<Boolean> checkLike(@PathVariable Long postId) {
        // 从JWT token中获取用户ID
        Long userId = SecurityUtils.getCurrentUserId(jwtUtil);
        
        if (userId == null) {
            return ApiResponse.error(401, "用户未认证");
        }
        
        boolean isLiked = likeService.isLiked(postId, userId);
        return ApiResponse.success("查询成功", isLiked);
    }

    @GetMapping("/count")
    @Operation(summary = "获取帖子点赞数")
    public ApiResponse<Integer> getLikeCount(@PathVariable Long postId) {
        int likeCount = likeService.getLikeCount(postId);
        return ApiResponse.success("查询成功", likeCount);
    }

    /**
     * 统一API响应格式
     */
    public static class ApiResponse<T> {
        private int code;
        private String msg;
        private T data;

        public ApiResponse(int code, String msg, T data) {
            this.code = code;
            this.msg = msg;
            this.data = data;
        }

        public static <T> ApiResponse<T> success(String msg, T data) {
            return new ApiResponse<>(200, msg, data);
        }

        public static <T> ApiResponse<T> error(int code, String msg) {
            return new ApiResponse<>(code, msg, null);
        }

        // getters
        public int getCode() { return code; }
        public String getMsg() { return msg; }
        public T getData() { return data; }
    }
}
